package controllers;


import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import models.Map;
import views.GameView;

public class SpawnedMobsController {
	
	private GameView gameView;
	private Map map;
	private int numMobsToSpawn;
	private int sleepTime;
	private int level;
	private int mobID;
	private static List<Thread> threadList;
	private static boolean enable=true;
	public static final int DEFAULT_NUM_MOBS = 4;
	public static final int DEFAULT_SLEEP_TIME = 3000;
	
	//Construtor
	public SpawnedMobsController(GameView gameView, Map map, int level){
		this.gameView = gameView;
		this.map = map;
		this.level = level;
		this.mobID = 1;
		this.numMobsToSpawn = DEFAULT_NUM_MOBS * level;
		this.sleepTime = DEFAULT_SLEEP_TIME;
		threadList = new CopyOnWriteArrayList<Thread>();
	}
	
	//Setters
	public static void setEnable(boolean enable){
		SpawnedMobsController.enable = enable;
	}
	
	//Getters
	public static List<Thread> getThreadList(){
		return threadList;
	}
	
	public static boolean getEnable(){
		return enable;
	}
	
	public static void interruptThread(Thread thread){
		threadList.remove(thread);
		thread.interrupt();
	}
	
	public static void interruptThreadEndOfGame(Thread thread){
		enable = false;
		for(Thread t: threadList){
			if(t != thread){
				threadList.remove(t);
				t.interrupt();
			}
		}
	}
	
	public static void insertThread(Thread thread){
		threadList.add(thread);
	}
	
	public void initMobs(){
		SpawnedMobsThread spawnedMobsThread = new SpawnedMobsThread();
		spawnedMobsThread.start();
	}
	
	class SpawnedMobsThread extends Thread{
		
		public void run() {
			while(numMobsToSpawn>0 && enable){
				MobController mobController = new MobController(gameView, map, this, level, mobID);
				mobController.initMob();
				numMobsToSpawn--;
				mobID++;
				try {
					sleep(sleepTime);
				} catch (InterruptedException e) {
					interrupt();
					e.printStackTrace();
				}
			}
			this.interrupt();
		}
		
		//Getters
		public int getNumMobsToSpawn(){
			return numMobsToSpawn;
		}
		
	}
	
	

}
